

from qtpy import QtCore
from qtpy import QtWidgets
from qtpy import QtGui


class LabelDialog(QtWidgets.QDialog):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        # 显示提示信息
        self.labelname_label = QtWidgets.QLabel()
        self.labelname_label.setText(self.tr("名称"))
        # 显示类别的下拉列表
        self.label_combobox = QtWidgets.QComboBox()

        # 确认取消按钮
        self.buttonBox = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal,
            self,
        )

        # 创建布局
        self.labelname_layout = QtWidgets.QHBoxLayout()
        self.labelname_layout.addWidget(self.labelname_label)
        self.labelname_layout.addWidget(self.label_combobox)
        self.main_layout = QtWidgets.QVBoxLayout()
        self.attr_layout = QtWidgets.QVBoxLayout()
        # 添标签控件
        self.main_layout.addLayout(self.labelname_layout)
        self.main_layout.addLayout(self.attr_layout)
        # 添加取消确认按钮
        self.main_layout.addWidget(self.buttonBox)
        # 设置窗口布局
        self.setLayout(self.main_layout)
        self.labels_info = None
        self.label_attr_info = {}
        # 当前标签名称
        self.current_labelname = ""

        # 链接相关函数
        self.connectFunc()

    def clearInfo(self):
        self.labels_info = None
        self.label_attr_info = {}
        # 当前标签名称
        self.current_labelname = ""

    def connectFunc(self):
        # 确认按钮
        self.buttonBox.accepted.connect(self.onAccepted)
        # 取消按钮
        self.buttonBox.rejected.connect(self.reject)
        # 当下拉列表的当前显示的信息改变时，触发函数self.onLabelNameComboBoxChang
        self.label_combobox.currentIndexChanged.connect(self.onLabelNameComboBoxChange)

    def onLabelNameComboBoxChange(self, index):
        sender = self.sender()
        self.updateAttrWidget(sender.currentText())

    def create_attrs(self, labels_info):
        # 处理所有的标签
        for onelabel in labels_info:
            # 处理当前类别
            self.create_label_attr(onelabel)

    def create_label_attr(self, onelabel):
        # 类别名称
        label_name = onelabel["name"]
        # 当前属性的布局
        v_layout = QtWidgets.QVBoxLayout()
        # 循环处理属性
        save_info = {}
        for one_attr in onelabel["attributes"]:
            current_widet = {}
            # 属性名称
            attr_name = one_attr["attr_name"]
            # 属性值
            attr_values = one_attr["attr_value"]
            # 显示属性名称的控件
            attr_label = QtWidgets.QLabel()

            # 设置属性名称
            attr_label.setText(attr_name)
            # 创建属性值列表
            attr_combobox = QtWidgets.QComboBox()

            attr_combobox.addItems(attr_values)
            h_layout = QtWidgets.QHBoxLayout()
            h_layout.addWidget(attr_label)
            h_layout.addWidget(attr_combobox)
            v_layout.addLayout(h_layout)

            current_widet["label"] = attr_label
            current_widet["comobbox"] = attr_combobox
            current_widet["h_layout"] = h_layout

            save_info[attr_name] = current_widet
        save_info["v_layout"] = v_layout

        self.label_attr_info[label_name] = save_info

    def removeLayout(self, parent_layout, layout_to_remove):
        """从一个布局中删除另一个布局"""
        for i in range(parent_layout.count()):
            item = parent_layout.itemAt(i)
            if item.layout() == layout_to_remove:
                # 如果找到要删除的布局，则移除它
                parent_layout.removeItem(item)
                break

    def showAttrWidget(self, label_name, show=True):
        # 显示隐藏属性相关的控件
        if label_name == "":
            return
        for key, value_widgets in self.label_attr_info[label_name].items():
            if key != "v_layout":
                for widget_type, attr_widget in value_widgets.items():
                    if widget_type != "h_layout":
                        attr_widget.setVisible(show)

    def updateAttrWidget(self, label_name):
        # 获取更新之前的标签
        current_labelname = self.current_labelname
        if current_labelname != "":
            # 隐藏对应的控件
            self.showAttrWidget(current_labelname, show=False)
        # 更新当前标签
        self.current_labelname = label_name

        if label_name != "":
            # 显示当前标签控件
            self.showAttrWidget(label_name)
        # 删除 ok
        self.main_layout.removeWidget(self.buttonBox)
        # 删除属性布局
        self.removeLayout(self.main_layout, self.attr_layout)

        # 更新属性布局
        if label_name == "":
            # label_combobox.clear()
            self.attr_layout = QtWidgets.QVBoxLayout()
        else:
            self.attr_layout = self.label_attr_info[label_name]["v_layout"]
        # 添加属性布局
        self.main_layout.addLayout(self.attr_layout)
        # 添加 ok
        self.main_layout.addWidget(self.buttonBox)

    def setLabelInfo(self, labels_info):
        """设置当前标签信息"""

        # 隐藏旧的
        self.showAttrWidget(self.current_labelname, show=False)
        self.label_attr_info = {}
        self.labels_info = labels_info
        self.create_attrs(labels_info)
        if len(self.labels_info) > 0:
            # 清除旧的列表
            self.label_combobox.clear()
            for current_label in self.labels_info:
                # self.current_labelname  第一次addItem会更新
                self.label_combobox.addItem(current_label["name"])

    def getCurrentLabelInfo(self):
        ret = {}
        label_name = self.current_labelname
        # 判断是否存在属性
        if label_name in self.label_attr_info:
            # 获取属性信息
            ret["name"] = label_name
            ret["attributes"] = []
            label_attr_info = self.label_attr_info[label_name]
            for attr_name, attr_widget_info in label_attr_info.items():
                attr_value = None
                if attr_name == "v_layout":
                    continue
                if "comobbox" in attr_widget_info:
                    attr_value = attr_widget_info["comobbox"].currentText()
                if attr_value is not None:
                    ret["attributes"].append({
                        "attr_name": attr_name,
                        "attr_value": attr_value
                    })
        return ret

    def onAccepted(self):
        """如果没有输入则不会退出窗口"""
        self.accept()


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ex = LabelDialog()
    with open("/home/dongzf/桌面/workspace/FreeLabel/freelabel/data/002/categories.json") as obj:
        import json
        data = json.load(obj)
        ex.setLabelInfo(data)
    if ex.exec_():
        label_info = ex.getCurrentLabelInfo()
        a = 1
    else:
        b = 1
    # ex.show()
    sys.exit(app.exec_())
